package com.tokenmaster.aitrade.market.okex;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.tokenmaster.aitrade.common.system.IndexConfig;
import com.tokenmaster.aitrade.common.system.KLinePoint;
import com.tokenmaster.aitrade.common.system.Order_Spot;
import com.tokenmaster.aitrade.common.ticker.Ticker_Spot;
import com.tokenmaster.aitrade.market.okex.spot.ISpotRestApi;
import com.tokenmaster.aitrade.market.okex.spot.SpotRestApi;

/**
 * 现货 REST API 客户端请求
 * 
 * @author
 *
 */
public class Market_Okex_Spot {

	private Logger logger = Logger.getLogger(this.getClass());

	private static Market_Okex_Spot instance = new Market_Okex_Spot();

	public static Market_Okex_Spot getInstance() {
		return instance;
	}

	// OKCoin申请的apiKey
	String api_key = "acc0c249-c5a5-40aa-a398-c978bb832ffb";
	// OKCoin 申请的secret_key
	String secret_key = "3725F86BA84B6CF9292C3949C497D490";
	// 注意：请求URL 国际站https://www.okcoin.com 国内站https://www.okcoin.cn
	String url_prex = "https://www.okex.com";

	/**
	 * get请求无需发送身份认证,通常用于获取行情，市场深度等公共信息
	 * 
	 */
	ISpotRestApi iSpotRestApiGet = new SpotRestApi(url_prex);

	/**
	 * post请求需发送身份认证，获取用户个人相关信息时，需要指定api_key,与secret_key并与参数进行签名，
	 * 此处对构造方法传入api_key与secret_key,在请求用户相关方法时则无需再传入， 发送post请求之前，程序会做自动加密，生成签名。
	 * 
	 */
	ISpotRestApi iSpotRestApiPost = new SpotRestApi(url_prex, api_key, secret_key);

	public double getTicker(String symbol) throws IOException {
		// 现货行情信息
		String tickerStr_Spot = iSpotRestApiGet.ticker(symbol);

		JSONObject jsonObject = JSONObject.parseObject(tickerStr_Spot);
		JSONObject jsonTicker = jsonObject.getJSONObject("ticker");
		return jsonTicker.getDoubleValue("last");
	}

	public Ticker_Spot getTicker_Spot(String symbol) throws IOException {
		Ticker_Spot ticker_Spot = new Ticker_Spot();

		// 现货行情信息
		String tickerStr_Spot = iSpotRestApiGet.ticker(symbol);

		JSONObject jsonObject = JSONObject.parseObject(tickerStr_Spot);

		ticker_Spot.setDate(jsonObject.getString("date"));

		JSONObject jsonTicker = jsonObject.getJSONObject("ticker");

		ticker_Spot.setLast(jsonTicker.getString("last"));
		return ticker_Spot;
	}

	public void addOrder(Order_Spot order_Spot) throws IOException {

		String resultJson = iSpotRestApiPost.trade(order_Spot.getSymbol(), order_Spot.getType(),
				String.valueOf(order_Spot.getPrice()), String.valueOf(order_Spot.getAmount()));

		JSONObject jsonObject = JSONObject.parseObject(resultJson);

		String result = jsonObject.getString("result");
		if (result.equals("true")) {
			order_Spot.setOrderId(jsonObject.getInteger("order_id"));
		}
	}

	/**
	 * 获取现货K线
	 * 
	 * @param indexConfig
	 * @return
	 * @throws Exception
	 */
	public List<KLinePoint> getKLines(IndexConfig indexConfig) throws Exception {
		// 返回值
		List<KLinePoint> kLinePoints = new ArrayList<KLinePoint>();

		String klineStr = null;// iSpotRestApiGet.kline(symbol, contract_type,
								// type);
		try {
			klineStr = iSpotRestApiGet.spot_kline(indexConfig.getSymbol(), indexConfig.getTypes_Enum().getKeyWord());
		} catch (IOException e) {
			logger.error("获取OkexK线数据为空，原因：参数或者网络");
			e.printStackTrace();
		}

		// TODO Auto-generated catch block

		// 字符串转换成Klines对象
		// 解析json 字符串
		JSONArray array = JSONArray.parseArray(klineStr);

		for (int i = 0; i < array.size(); i++) {

			KLinePoint kLinePoint = new KLinePoint();

			// 转换成数组
			Double[] array_Klines = array.getObject(i, Double[].class);
			BigDecimal bg = new BigDecimal(array_Klines[0]);
			long unixtime = bg.longValue();

			kLinePoint.setSymbol(indexConfig.getSymbol());
			kLinePoint.setType(indexConfig.getTypes_Enum().getKeyWord());
			kLinePoint.setUnixTime(unixtime);
			kLinePoint.setOpen(array_Klines[1]);
			kLinePoint.setHigh(array_Klines[2]);
			kLinePoint.setLow(array_Klines[3]);
			kLinePoint.setLast(array_Klines[4]);
			kLinePoint.setVol(array_Klines[5]);

			kLinePoints.add(kLinePoint);
		}

		return kLinePoints;
	}

	public List<KLinePoint> getKLines(String symbol, String type) throws Exception {
		// 返回值
		List<KLinePoint> kLinePoints = new ArrayList<KLinePoint>();

		String klineStr = null;// iSpotRestApiGet.kline(symbol, contract_type,
								// type);
		try {
			klineStr = iSpotRestApiGet.spot_kline(symbol, type);
		} catch (IOException e) {
			logger.error("获取OkexK线数据为空，原因：参数或者网络");
			e.printStackTrace();
		}

		// TODO Auto-generated catch block

		// 字符串转换成Klines对象
		// 解析json 字符串
		JSONArray array = JSONArray.parseArray(klineStr);

		for (int i = 0; i < array.size(); i++) {

			KLinePoint kLinePoint = new KLinePoint();

			// 转换成数组
			Double[] array_Klines = array.getObject(i, Double[].class);
			BigDecimal bg = new BigDecimal(array_Klines[0]);
			long unixtime = bg.longValue();

			kLinePoint.setSymbol(symbol);
			kLinePoint.setType(type);
			kLinePoint.setUnixTime(unixtime);
			kLinePoint.setOpen(array_Klines[1]);
			kLinePoint.setHigh(array_Klines[2]);
			kLinePoint.setLow(array_Klines[3]);
			kLinePoint.setLast(array_Klines[4]);
			kLinePoint.setVol(array_Klines[5]);

			kLinePoints.add(kLinePoint);
		}
		
		logger.info("获取到 " + array.size() + " 条K线");

		return kLinePoints;
	}

	/**
	 * 获取现货订单信息
	 * 
	 * @param symbol
	 * @param orderId
	 * @throws IOException
	 */
	public Order_Spot getOrderInfo(String symbol, String orderId) throws IOException {

		Order_Spot result_Order_Spot = null;

		String resultJson = iSpotRestApiPost.order_info(symbol, orderId);

		JSONObject jsonObject = JSONObject.parseObject(resultJson);
		String result = jsonObject.getString("result");
		if (result.equals("true")) {

			JSONArray jsonArray = jsonObject.getJSONArray("orders");

			if (jsonArray.size() > 0) {
				result_Order_Spot = JSONObject.parseObject(jsonArray.get(jsonArray.size() - 1).toString(),
						new TypeReference<Order_Spot>() {
						});
			}

		}

		return result_Order_Spot;
	}

	public void cancelOrder(String symbol, String orderId) throws IOException {
		// 现货撤销订单
		iSpotRestApiPost.cancel_order(symbol, orderId);
	}

	// // 现货行情
	// stockGet.ticker("btc_usdt");
	//
	// // 现货市场深度
	// stockGet.depth("btc_usd");
	//
	// // 现货OKCoin历史交易信息
	// stockGet.trades("btc_usd", "20");
	//
	// // 现货用户信息
	// stockPost.userinfo();
	//
	// // 现货下单交易
	// String tradeResult = stockPost.trade("btc_usd", "buy", "50", "0.02");
	// System.out.println(tradeResult);
	// JSONObject tradeJSV1 = JSONObject.parseObject(tradeResult);
	// String tradeOrderV1 = tradeJSV1.getString("order_id");
	//
	// // 现货获取用户订单信息
	// stockPost.order_info("btc_usd", tradeOrderV1);
	//

	//
	// // 现货批量下单
	// stockPost.batch_trade("btc_usd", "buy", "[{price:50,
	// amount:0.02},{price:50, amount:0.03}]");
	//
	// // 批量获取用户订单
	// stockPost.orders_info("0", "btc_usd", "125420341, 125420342");
	//
	// // 获取用户历史订单信息，只返回最近七天的信息
	// stockPost.order_history("btc_usd", "0", "1", "20");

}
